import sys, pygame, time, random, os, traceback, math
import pymunk
sys.path.append(os.path.abspath( os.path.dirname(sys.argv[0])+'/jplur/' ) )
import jplur
pygame.init()


mapkey = {(0,0,0):0, (57,181,74):1, (0,174,239):2, (192,159,66):3, (255,255,255):4}
propkey = {(255,156,0):2, (255,0,6):1, (222,0,255):0 }
sausagekey = { (0,204,255):3, (4,177,220):4, (3,153,191):5,(0,133,160):6, (0,105,126):7, (0,72,87):10 }
tile_edge_key = { 1:[0,-1],
		2:[0,2],
		3:[1,0],
		4:[0,0],
		5:[1,1],
		6:[3,0],
		7:[5,0],
		8:[0,1],
		9:[3,1],
		10:[1,-1],
		11:[5,-1],
		12:[1,2],
		13:[5,1],
		14:[5,2],
		15:[4,0] }
		
edge_type_key = { 1:6,2:12,3:18,4:24 }
#edge_type_key = { 3:18 }
edge_shadow_key = {1:30, 2:30, 3:30, 4:24 }		

#collision types
WALL_LEFT = 0
WALL_RIGHT = 1
WALL_TOP = 2
WALL_BOTTOM = 3
DOG_PART = 4

THELEVEL = 0

def amnesia(level, loser):
	THELEVEL = jplur.brain.current_level
	jplur.brain = Brain()
	jplur.brain.current_level = level
	jplur.brain.loser = loser
	jplur.brain.setup()
	


levels = {'breakout':['map.sheet.6.6.32.32.png', 60 ,30, 'info_1.png', 'Help your hotdog escape to the exit!' ],
		'steps':['map.sheet.6.6.32.32.png', 80 ,20, 'info_2.png', 'Pretty good, now try some stairs.' ],
		'steps2':['map.sheet.6.6.32.32.png', 90 ,30, 'default.png', "You didn't think you were alone, did you?" ],
		'top':['map.sheet.6.6.32.32.png', 100 ,30, 'default.png', 'Don"t fall!' ],
		'blackflag':['map.sheet.6.6.32.32.png', 100 ,50, 'default.png', 'Oh no, is that lava?' ],
		'funnel':['map.sheet.6.6.32.32.png', 80 ,80, 'default.png', 'Sometimes you got to squeeze..' ],
		'hurry':['map.sheet.6.6.32.32.png', 100 ,50, 'default.png', 'Notice the timer in the corner.' ],
		'city2':['map.sheet.6.6.32.32.png', 50 ,100, 'default.png', 'Why did they make so many holes?' ],
		'island':['map.sheet.6.6.32.32.png', 50 ,100, 'info_10.png', 'Things are heating up in here.' ],
		'winner':['map.sheet.6.6.32.32.png', 100 ,999999, 'you_won.png', 'YOU SIR, HAVE WON THE GAME' ]} 
levellist = ['breakout', 'steps', 'steps2', 'top', 'blackflag', 'funnel', 'hurry', 'city2', 'island', 'winner']
		
def normalize(p1,p2):
	L = math.sqrt(p1 * p1 + p2 * p2)
	return [p1/L, p2/L]

def GetInHMS(seconds):
    hours = seconds / 3600.0
    seconds -= 3600.0*hours
    minutes = seconds / 60.0
    seconds -= 60.0*minutes
    if hours == 0.0:
        return "%02d:%02d" % (minutes, seconds)
    return "%02d:%02d:%02d" % (hours, minutes, seconds)

def dist(p1, p2):
	x = p1[0] - p2[0]
	y = p1[1] - p2[1]
	return math.sqrt(pow(x, 2) + pow(y,2))
	
class Brain:
	def __init__(self):
		pygame.init()
		pygame.mixer.init()
		self.size = self.width, self.height = 960, 640
		pymunk.init_pymunk()
		self.space = pymunk.Space() #3
		self.space.gravity = (0.0, -400.0)
		self.space._space.contents.elasticIterations = 0
		self.screen = pygame.display.set_mode(self.size)
		pygame.image.get_extended()
		
		self.terminal = pygame.font.Font(os.path.dirname(sys.argv[0])+'/vgaoem.fon', 64)
		
		self.splat = pygame.mixer.Sound(os.path.dirname(sys.argv[0])+'/splat.wav')
		self.gross = pygame.mixer.Sound(os.path.dirname(sys.argv[0])+'/gross.wav')
		self.yay = pygame.mixer.Sound(os.path.dirname(sys.argv[0])+'/yay.wav')
		
		self.yay.set_volume(.5)
		self.gross.set_volume(.5)
		self.splat.set_volume(.5)
		
		self.keysdown = {276:0,275:0,273:0,119:0,97:0,100:0}
		self.space.add_collision_handler(100, DOG_PART, None, None,self.touch_exit, None)
		self.space.add_collision_handler(101, DOG_PART, None, None,self.touch_lava, None)
		self.space.add_collision_handler(102, DOG_PART, None, None,self.touch_spikes, None)
		
		self.show_ui = False
		
		self.current_level = THELEVEL
		self.loser = 0
		
	def setup(self):
		self.maps, self.sheets = {}, {}
		self.sheets['tiles'] = Spritesheet('map.sheet.6.6.32.32.png')
		self.sheets['tiles2'] = Spritesheet('map2.sheet.6.6.32.32.png')
		self.sheets['hotdog'] = Spritesheet('hotdog.sheet.1.3.64.32.png')
		self.sheets['powerups'] = Spritesheet('powerups.sheet.2.2.32.32.png')
		
		self.load(levellist[self.current_level])
		
		
	def update(self):
		if self.show_ui:
			self.ui()
		else:
			self.time_left = int( self.time_limit-(time.time() - self.level_start_time))
			self.space.step(1.0/50.0)
			self.map.draw()
			for entry in self.entities:
				entry.update()
			for entry in self.powerups:
				entry.update()
			self.HUD()
			#print '*',len(self.powerups)
			"""
			for entry in self.space.shapes:

				p = entry.body.position
				p = [p[0],640 - p[1] ]
				pygame.draw.circle(self.screen, (255,0,0), p, 4, 0)"""
				
			total_meat = 0
			for entry in self.entities:
				total_meat += len(entry.parts)
			if (total_meat == 0 and self.time_left < 20) or self.time_left < 0:
				self.meat_lost += total_meat
				print "YOU FINISHED"
				total = self.meat_escaped + self.meat_lost
				if total == 0:
					total = 0.001
				esp = int((float(self.meat_escaped) / float(total)) * 100)
				lsp = int((float(self.meat_lost) / float(total)) * 100)
				print esp, lsp
				if esp < self.level[1]:
					self.loser = 1
				else:
					self.current_level += 1
				
				
				amnesia(self.current_level, self.loser)
				del self
				
	def ui(self):
		level = levels[self.show_ui]
		self.screen.fill( (0,0,0) )
		bit = level[4]
		if self.loser == 1:
			bit = "Not enough sausages escaped that time, try again!"
		
		blurb = self.terminal.render(bit, 1, (255, 255, 255))
		textpos = blurb.get_rect(centerx=self.screen.get_width()/2, y=300)
		self.screen.blit(blurb, textpos)
		
		blurb = self.terminal.render('Press the any key to begin', 1, (255, 255, 255))
		textpos = blurb.get_rect(centerx=self.screen.get_width()/2, y=370)
		self.screen.blit(blurb, textpos)
		
		if level[3] and self.loser == 0:
			self.ui_image = pygame.image.load(os.path.dirname(sys.argv[0])+'/maps/'+level[3])
			self.screen.blit(self.ui_image, self.ui_image.get_rect(centerx = self.screen.get_width()/2, y=120) )
		
			
	def HUD(self):
		bar = pygame.Surface( (960, 15)  )
		self.screen.blit(bar, bar.get_rect())
		
		tt = str(self.time_left)
		timeleft = self.terminal.render("TIME LEFT: "+tt, 1, (255, 255, 255))
		title = self.terminal.render("//// ESCAUSAGE \\\\\\\\", 1, (255, 255, 255))
		escaped = self.terminal.render("MEAT ESCAPED: "+str(self.meat_escaped), 1, (255, 255, 255))
		lost = self.terminal.render("MEAT LOST: "+str(self.meat_lost), 1, (255, 255, 255))
		textpos = timeleft.get_rect(x=850)
		self.screen.blit(timeleft, textpos)
		textpos = title.get_rect(x=440)
		self.screen.blit(title, textpos)
		textpos = escaped.get_rect(x=10)
		self.screen.blit(escaped, textpos)
		textpos = lost.get_rect(x=200)
		self.screen.blit(lost, textpos)
		
	def load(self, level):
		
		self.show_ui = level
		
		
	def load_internal(self, level):
		for entry in self.space.shapes:
			self.space.remove(entry)
		self.show_ui = None
		self.loser = 0
		self.entities = []
		self.powerups = []
		self.level = levels[level]
		self.map = Map(self.screen, level+'.png')
		self.time_limit = self.level[2]
		self.level_start_time = time.time()
		
		self.meat_lost = 0
		self.meat_escaped = 0
	
	def touch_exit(self, a,b):
		if self.yay.get_num_channels() < 30:
			self.yay.play(maxtime = 100)
		arbiter = b
		chosen =  arbiter.shapes[1]
		
		for meat in self.entities:
			to_remove = False
			for segment in meat.parts:
				if segment == chosen:
					meat.destroy(chosen)
					jplur.brain.meat_escaped += 1
		
	def touch_lava(self, a,b):
		if self.gross.get_num_channels() < 30:
			self.gross.play(maxtime = 100)
		arbiter = b
		chosen =  arbiter.shapes[1]
		
		for meat in self.entities:
			to_remove = False
			for segment in meat.parts:
				if segment == chosen:
					meat.destroy(chosen)
					jplur.brain.meat_lost += 1
					
	def touch_spikes(self, a,b):
		if self.gross.get_num_channels() < 30:	
			self.gross.play(maxtime = 100)
		arbiter = b
		chosen =  arbiter.shapes[1]
		
		for meat in self.entities:
			to_remove = False
			for segment in meat.parts:
				if segment == chosen:
					meat.destroy(chosen)
					jplur.brain.meat_lost += 1
	
			
	def handle_mousedown(self, pos):
		self.entities.append(Hotdog(self.screen, self.sheets['hotdog'], pos, 8) )
	def handle_keydown(self, key):
		if self.show_ui:
			self.load_internal(self.show_ui)
		elif key == 114:
			self.load(levellist[self.current_level])
		if key in self.keysdown:
				self.keysdown[key] = 1
	def handle_keyup(self, key):
		if key in self.keysdown:
			self.keysdown[key] = 0

class Spritesheet:
	def __init__(self, filename):
		self.image = pygame.image.load(os.path.dirname(sys.argv[0])+'/sprites/'+filename)
		self.image = self.image.convert_alpha()
		self.tiles = []
		sp = filename.split('.')
		self.name = sp[0]
		self.sheet_x = int(sp[2])
		self.sheet_y = int(sp[3])
		self.image_x = int(sp[4])
		self.image_y = int(sp[5])
		
		for y in range(self.sheet_y):
			for x in range(self.sheet_x):
				rect = pygame.Rect(x*self.image_x,y*self.image_y,self.image_x,self.image_y)
				tile = pygame.Surface(rect.size, pygame.SRCALPHA)
				tile.convert_alpha()
				tile.blit(self.image, (0,0), rect)
				
				#tile.set_colorkey(colorkey, pygame.RLEACCEL)
				self.tiles.append(tile)

class Map:
	def __init__(self, parent, filename):
		self.parent = parent
		self.load(filename)
		
		
	def load(self, filename):
		""" Loads a .map file. """
		self.image = pygame.image.load(os.path.dirname(sys.argv[0])+'/maps/'+filename)
		self.prop_image = pygame.image.load(os.path.dirname(sys.argv[0])+'/maps/'+filename.split('.')[0]+'_props.png')
		print "^", self.image.get_width(), self.prop_image.get_width()
		self.width = self.image.get_width()
		self.height = self.image.get_height()
		self.surface = pygame.Surface( (self.width*32, self.height*32) ).convert_alpha()
		self.surface.fill((255,0,0))
		
		self.array = []
		#pymunk stuff
		self.body = pymunk.Body(pymunk.inf, pymunk.inf) # 1
		self.body.position = (0,0) 
		
		self.top = pymunk.Body(pymunk.inf, pymunk.inf) # 1
		self.top.position = (0,0) 
		self.bottom = pymunk.Body(pymunk.inf, pymunk.inf) # 1
		self.bottom.position = (0,0) 
		self.left = pymunk.Body(pymunk.inf, pymunk.inf) # 1
		self.left.position = (0,0) 
		self.right = pymunk.Body(pymunk.inf, pymunk.inf) # 1
		self.right.position = (0,0) 
		segments = []
		for i in range(self.height):
			temp = []
			for j in range(self.width):
				temp.append(0)
			self.array.append(temp)
		pxarray = pygame.PixelArray(self.image)
		for x in range(self.width):
			for y in range(self.height):
				found = self.image.unmap_rgb( pxarray[x][y] )
				self.array[y][x] = mapkey[ tuple(found)[:3] ]
				if self.array[y][x] in [4]:
					square = pymunk.Poly(self.body, [(x*32, 640-y*32), (x*32+32, 640-y*32), (x*32+32, 640-y*32-32),  (x*32, 640-y*32-32) ] )
					
					square.friction = 1
					square.elasticity = .5
					jplur.brain.space.add_static(square)

		#now add the powerups
		pxarray = pygame.PixelArray(self.prop_image)
		print("RUN ONCE")
		for x in range(self.width):
			
			for y in range(self.height):
				found = tuple(self.image.unmap_rgb( pxarray[x][y] ))[:3]
				if tuple(found) in propkey:

						jplur.brain.powerups.append( Powerup(jplur.brain.screen, jplur.brain.sheets['powerups'], (x*32, y*32), propkey[found] ) )
				if tuple(found) in sausagekey:
						print "FOUND  SAUSASGE"
						jplur.brain.entities.append( Hotdog(jplur.brain.screen, jplur.brain.sheets['hotdog'], (x*32, y*32), sausagekey[tuple(found)]) )
		self.setup()
	
	def setup(self):
		to_do = [0,1,2,3,4]
		print len(self.array)-1, "!!!!"
		for i in to_do:
			for y in range(self.height):
				for x in range(self.width):
					if self.array[y][x] == i:
						self.surface.blit(jplur.brain.sheets['tiles'].tiles[i], pygame.Rect(x*32,y*32,32,32))
					elif i in edge_type_key:
						if i in edge_shadow_key:
							self.fancy_tile(y,x,i, shadow=1)
						self.fancy_tile(y,x,i)
		
	
	def fancy_tile(self, y, x, to_do, shadow=0):
		edge = edge_type_key[to_do]
		offset = [0,0]
		if shadow == 1 and to_do in edge_shadow_key:

			edge = edge_shadow_key[to_do]
			offset = [2,2]
		found = 0
		corners = [0,0,0,0]
		if y > 0:
			if self.array[y-1][x] == to_do:
				found += 1
		if y < self.height-1:
			if self.array[y+1][x] == to_do:
				found += 8
		if x > 0:
			if self.array[y][x-1] == to_do:
				found += 2
		if x < self.width-1:
			if self.array[y][x+1] == to_do:
				found += 4

		if found in tile_edge_key:
			
			data = tile_edge_key[found]
			temp = pygame.Surface((32,32), pygame.SRCALPHA)
			temp.convert_alpha()
			temp.blit(jplur.brain.sheets['tiles'].tiles[data[0]+edge], pygame.Rect(0,0,32,32))
			temp = pygame.transform.rotate(temp, -90*data[1])
			self.surface.blit(temp, pygame.Rect(x*32+offset[0],y*32+offset[1],32,32))
			
		if found in [0,1,2,4,8,3,5,10,12]:
			try:
				if self.array[y-1][x-1] == to_do:
					temp = pygame.Surface((32,32), pygame.SRCALPHA)
					temp.blit(jplur.brain.sheets['tiles'].tiles[2+edge], pygame.Rect(0,0,32,32))
					temp = pygame.transform.rotate(temp, -90*-1)
					self.surface.blit(temp, pygame.Rect(x*32+offset[0],y*32+offset[1],32,32))
			except:
				pass
			try:
				if self.array[y-1][x+1] == to_do:
					temp = pygame.Surface((32,32), pygame.SRCALPHA)
					temp.blit(jplur.brain.sheets['tiles'].tiles[2+edge], pygame.Rect(0,0,32,32))
					self.surface.blit(temp, pygame.Rect(x*32+offset[0],y*32+offset[1],32,32))
			except:
				pass
			try:
				if self.array[y+1][x-1] == to_do:
					temp = pygame.Surface((32,32), pygame.SRCALPHA)
					temp.blit(jplur.brain.sheets['tiles'].tiles[2+edge], pygame.Rect(0,0,32,32))
					temp = pygame.transform.rotate(temp, -90*-2)
					self.surface.blit(temp, pygame.Rect(x*32+offset[0],y*32+offset[1],32,32))
			except:
				pass
			try:
				if self.array[y+1][x+1] == to_do:
					temp = pygame.Surface((32,32), pygame.SRCALPHA)
					temp.blit(jplur.brain.sheets['tiles'].tiles[2+edge], pygame.Rect(0,0,32,32))
					temp = pygame.transform.rotate(temp, -90*1)
					self.surface.blit(temp, pygame.Rect(x*32+offset[0],y*32+offset[1],32,32))
			except:
				pass
	
	def update(self):
		pass
	def draw(self):
		self.parent.blit(self.surface, pygame.Rect(0,0,32,32))
	
class Entity:
	def __init__(self, parent, sheet):
		
		self.parent = parent
		self.sheet = sheet
		self.rect = pygame.Rect(0,0, sheet.image_x, sheet.image_y)
		self.rect = self.rect.move( [0, 0] )
		self.animation = [0,1,2,3,4,5,6,7,8,9,10]
		self.animspeed = random.random()*.4+.1
		self.speed = [int(1/self.animspeed*.5)]*2

		self.oldtime = time.time()
	
	def update(self):
		self.rect = self.rect.move(self.speed)
		if self.rect.right < 0:
			self.rect.left = width
		elif self.rect.left > width:
			self.rect.right = 0
		if self.rect.bottom < 0:
			self.rect.top = height
		elif self.rect.top > height:
			self.rect.bottom = 0
	
	def draw(self):
		if time.time()-self.oldtime > .5*self.animspeed:
			self.oldtime = time.time()
			self.animation = self.animation[1:]+self.animation[:1]
		self.parent.blit(self.sheet.tiles[self.animation[0]], self.rect)	
	
class Powerup:
	def __init__(self, parent, sheet, pos=[0,0], type=0):
		self.body = pymunk.Body(pymunk.inf, pymunk.inf) # 1
		self.body.position = pymunk.vec2d.Vec2d(pos[0], 640-pos[1]) 
		print type, "$$$$", self.body.position
		self.parent = parent
		self.sheet = sheet
		self.type = type
		self.rect = pygame.Rect(0,0, sheet.image_x, sheet.image_y)
		self.rect = self.rect.move( pos )
		l1 = pymunk.Segment(self.body, (0, 0), (32, 0), 5.0 )
		l2 = pymunk.Segment(self.body, (0, -32), (32,  - 32), 5.0 )
		l3 = pymunk.Segment(self.body, (0, 0), (0,-32), 5.0 )
		l4 = pymunk.Segment(self.body, (32, 0), (32, -32), 5.0 )
		l1.collision_type, l2.collision_type, l3.collision_type, l4.collision_type = type+100, type+100, type+100, type+100
		jplur.brain.space.add_static(l1,l2,l3,l4)
		
	def update(self):
		self.draw()
	
	def draw(self):
		self.parent.blit(self.sheet.tiles[self.type], self.rect)
		#pygame.draw.circle(self.parent, (255,0,0), self.body.position, 4, 0)
		
class Dynamic(Entity):
	def __init__(self, parent, sheet, pos):
		self.pos = pos
		self.pos = (self.pos[0], jplur.brain.height - self.pos[1])
		Entity.__init__(self, parent, sheet)
		self.shape = self.setup()
		self.birthtime = time.time()
		
	def setup(self):
		mass = 1
		radius = 11
		inertia = pymunk.moment_for_circle(mass, 0, radius) # 1
		self.body = pymunk.Body(mass, inertia) # 2
		x = random.randint(120,380)
		self.body.position = self.pos[0], self.pos[1] # 3
		shape = pymunk.Circle(self.body, radius) # 4
		jplur.brain.space.add(self.body, shape) # 5
		return shape
		
	def update(self):
		if time.time()-self.birthtime < 5:
			self.draw()
		else:
			self.draw()
			#self.kill()
	def draw(self):
		p = int(self.shape.body.position.x)-16, 640-int(self.shape.body.position.y)-16
		if time.time()-self.oldtime > .5*self.animspeed:
			self.oldtime = time.time()
			self.animation = self.animation[1:]+self.animation[:1]
		self.rect = pygame.Rect(p, [32,32])
		self.parent.blit(self.sheet.tiles[self.animation[0]], self.rect)
	def kill(self):
		print(dir(space))
		space.remove(self.shape, self.body)
		toys.pop(self)
		del self
	def moveright(self):
		self.body.apply_force([30.0,0.0], r=(11,0))
	def moveleft(self):
		self.body.apply_force([-30.0,0.0], r=(-11,0))
	def jump(self):
		print "jump"
		self.body.apply_impulse([0.0,400.0], r=(0,10))
		
class Hotdog(Entity):
	def __init__(self, parent, sheet, pos, length, setup=1):
		self.pos = pos
		self.pos = (self.pos[0], jplur.brain.height - self.pos[1])
		Entity.__init__(self, parent, sheet)
		self.parts = []
		self.length = length
		self.buttsex = 0
		self.buttsex2 = 0
		if setup:
			self.setup()
		self.birthtime = time.time()
		
		self.jumplimit_l, self.jumplimit_r = 0, 0
		
	def mimic(self, segs):
		i = 0
		for seg in segs:
			self.parts[i].body.position = seg.body.position
			i += 1
		
	def setup(self):
		for part in range(self.length):
			mass = .1
			radius = 11
			inertia = pymunk.moment_for_circle(mass, 0, radius) # 1
			body = pymunk.Body(mass, inertia) # 2
			body.position = self.pos[0]+part*32, self.pos[1] # 3
			shape = pymunk.Circle(body, radius) # 4
			shape.friction = .9
			shape.elasticity = .5
			shape.collision_type = DOG_PART
			
			if len(self.parts) > 0:
				rotation_center_joint = pymunk.PinJoint(body, self.parts[ len(self.parts)-1 ].body, (0,0), (0,0))
				rotation_center_joint.max_bias = 50
				rotation_center_joint.biasCoef = 10
				rotation_center_joint.max_force = 2600
				#add the joint
				jplur.brain.space.add(body, shape, rotation_center_joint) # 5

			else:
				jplur.brain.space.add(body, shape ) # it's the first part of our dog
			self.parts.append(shape)
	
	def destroy(self, chosen):
		#determine if chosen splits the hotdog
		remove_end = 0
		remove_middle = 0
		m_ind = 0
		i = 0
		length = len(self.parts)-1
		for part in self.parts:
			if part == chosen:
				if i in [0,length]:
					remove_end = chosen
					
				else:
					remove_middle = chosen
					m_ind = i
					
			i += 1
		if remove_end:
			self.parts.remove(chosen)
			jplur.brain.space.remove(chosen.body, chosen)
			if length == 1:
				for thing in self.parts:
					jplur.brain.space.remove(thing.body, thing)
				self.kill()
				
		if remove_middle:

			right = self.parts[m_ind+1:]
			print right
			self.parts.remove(chosen)
			jplur.brain.space.remove(chosen)
			
			if len(right) > 1:
				newdog = Hotdog(jplur.brain.screen, jplur.brain.sheets['hotdog'], [0,0], len(right))
				jplur.brain.entities.append(newdog)
				newdog.mimic(right)
			
			for entry in right:
				self.parts.remove(entry)
				jplur.brain.space.remove(entry.body, entry)
				
			right = False
			if len(self.parts) == 1:
				for thing in self.parts:
					jplur.brain.space.remove(thing.body, thing)
				self.kill()
				
	
	def kill(self):
		if self in jplur.brain.entities:
			jplur.brain.entities.remove(self)
			del self
	
	def update(self):
		i = 0
		for part in self.parts:
			need_up = 0
			p = list( part.body.position )
			if p[0] < 32:
				p[0] = 32
				need_up = 1
			
			if need_up == 1:
				part.body.position = tuple(p)
				
			p = list(part.body.position)
			p = [int(p[0])/32, int(640-p[1])/32]
			#pygame.draw.circle(self.parent, (255,0,0), (p[0]*32+16, p[1]*32+16), 4, 0)	 
			if jplur.brain.map.array[p[1]][p[0]] in [4] and len(self.parts) > 2:
				g = len(self.parts)/2
				if i < g:
					part.body.position = self.parts[i+1].body.position
				else:
					
					part.body.position = self.parts[i-1].body.position
			i += 1
			
		self.draw()
		self.apply_keydown()
		self.length = len(self.parts)
	
	def draw(self):
		for i in range(len(self.parts)-1):
			p = int(self.parts[i].body.position.x), 640-int(self.parts[i].body.position.y)
			if i == 0:
				t = 0
			else:
				if i == len(self.parts)-2:
					t = 2
				else:
					t = 1
			if self.length == 1:
				t = 3
			surface = self.sheet.tiles[self.animation[t]]
			if i < len(self.parts)-1:
				
				p2 = int(self.parts[i+1].body.position.x), 640-int(self.parts[i+1].body.position.y)
				p1n = normalize(p[0],p[1])
				p2n = normalize(p2[0],p2[1])
				angle = math.atan2((p2[0]-p[0]), (p2[1]-p[1]))

				angle = math.degrees(angle) -90
				surface = pygame.transform.rotate(surface, angle)
				p3 = [ (p[0] + p2[0])/2, (p[1] + p2[1])/2]
				drawp = [ p3[0] - surface.get_width()/2, p3[1] - surface.get_height()/2 ]
				
			partrect = pygame.Rect(drawp, surface.get_size())
			self.parent.blit(surface, partrect)
			#pygame.draw.circle(self.parent, (255,0,0), p, 4, 0)
			#pygame.draw.circle(self.parent, (0,255,255), p3, 4, 0)
	
	def apply_keydown(self):
		if self.jumplimit_l > 0:
			self.jumplimit_l -= 1

		if self.jumplimit_r > 0:
			self.jumplimit_r -= 1

		force = math.pow(float(self.length), 3)*(self.length)
		m_f = force*2
		left_vel = list(self.parts[0].body.velocity)
		right_vel = list(self.parts[len(self.parts)-1].body.velocity)
		
		
		print self.length
		if self.length in [1]:
			force = 100
			m_f = 100
		if self.length in [2]:
			force = 50
			m_f = 50
		if self.length in [3]:
			force = 75
			m_f = 75
		if self.length in [4]:
			force = 100
			m_f = 100
		if self.length in [5,6]:
			force = 150
			m_f = 150
		if self.length in [7,8]:
			force = 200
			m_f = 200
		if self.length in [9,10]:
			force = 1000
			m_f = 1000
		
		##controll right half
		if dist(self.parts[ len(self.parts)-1 ].body.position, self.parts[ len(self.parts)-2 ].body.position) < 42 and self.length > 1:
			if jplur.brain.keysdown[273] > 0 and self.jumplimit_r == 0:
				self.buttsex = 1
				self.jumplimit_r = 66
			elif jplur.brain.keysdown[273] == 0 and self.jumplimit_r == 0:
				self.buttsex = 0
			if self.jumplimit_r > 45 and self.buttsex == 1:
				 
				right_vel[1] += force
			if jplur.brain.keysdown[276] > 0:
				right_vel[0] -= force
			if jplur.brain.keysdown[275] > 0:
				right_vel[0] += force
		
		if right_vel[0] < -m_f/self.length*2.6: right_vel[0] = -m_f/self.length*2.6
		if right_vel[0] > m_f/self.length*2.6: right_vel[0] = m_f/self.length*2.6
		#if right_vel[1] < -m_f: right_vel[1] = -m_f
		if right_vel[1] > m_f: right_vel[1] = m_f
		
		self.parts[len(self.parts)-1].body.velocity = pymunk.vec2d.Vec2d(right_vel[0], right_vel[1])
		
		## Left half
		if dist(self.parts[ 0 ].body.position, self.parts[ 1 ].body.position) < 42 and self.length > 2:
			if jplur.brain.keysdown[119] > 0 and self.buttsex2 == 0:
				self.buttsex2 = 1
			if jplur.brain.keysdown[119] > 0 and self.jumplimit_l == 0:

				self.jumplimit_l = 66
			elif jplur.brain.keysdown[119] == 0 and self.jumplimit_l == 0:
				self.buttsex2 = 0
			if self.jumplimit_l > 45 and self.buttsex2 == 1:
				left_vel[1] += force
			if jplur.brain.keysdown[97] > 0:
				left_vel[0] -= force
			if jplur.brain.keysdown[100] > 0:
				left_vel[0] += force
		
		if left_vel[0] < -m_f/self.length*2.6: left_vel[0] = -m_f/self.length*2.6
		if left_vel[0] > m_f/self.length*2.6: left_vel[0] = m_f/self.length*2.6
		#if left_vel[1] < -m_f: left_vel[1] = -m_f
		if left_vel[1] > m_f: left_vel[1] = m_f
		
		self.parts[0].body.velocity = pymunk.vec2d.Vec2d(left_vel[0], left_vel[1])